﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Kkbac.Temp.Libs
{
    /// <summary>
    /// 功能不定. Use Context.Item;
    /// </summary>
    public class MultiThemeRazorViewEngine : RazorViewEngine
    {
        private string _itemName;
        private const string _viewThemeFormatString = "%themename%";

        public MultiThemeRazorViewEngine(string itemName)
        {
            _itemName = itemName;

            AreaViewLocationFormats = new[] {
                "~/Areas/{2}/Views/{1}/{0}.cshtml", 
                "~/Areas/{2}/Views/Shared/{0}.cshtml", 
            };

            AreaMasterLocationFormats = AreaViewLocationFormats;
            AreaPartialViewLocationFormats = AreaViewLocationFormats;

            ViewLocationFormats = new[] {
                "~/Views/"+_viewThemeFormatString+"/{1}/{0}.cshtml", 
                "~/Views/"+_viewThemeFormatString+"/Shared/{0}.cshtml", 
                "~/Views/Global/{1}/{0}.cshtml", 
                "~/Views/Global/Shared/{0}.cshtml", 
            };

            MasterLocationFormats = ViewLocationFormats;
            PartialViewLocationFormats = ViewLocationFormats;

        }

        private string ReplaceThemeName(ControllerContext controllerContext, string path)
        {
            var themeName = Convert.ToString(controllerContext.HttpContext.Items[_itemName]);
            var pathNew = path.Replace(_viewThemeFormatString, themeName);

            return pathNew;
        }

        protected override IView CreatePartialView(ControllerContext controllerContext, string partialPath)
        {
            partialPath = ReplaceThemeName(controllerContext, partialPath);

            return base.CreatePartialView(controllerContext, partialPath);
        }

        protected override IView CreateView(ControllerContext controllerContext, string viewPath, string masterPath)
        {
            viewPath = ReplaceThemeName(controllerContext, viewPath);
            masterPath = ReplaceThemeName(controllerContext, masterPath);

            return base.CreateView(controllerContext, viewPath, masterPath);
        }

        protected override bool FileExists(ControllerContext controllerContext, string virtualPath)
        {
            try
            {
                virtualPath = ReplaceThemeName(controllerContext, virtualPath);

                return base.FileExists(controllerContext, virtualPath);
            }
            catch (HttpException exception)
            {
                if (exception.GetHttpCode() != 404)
                {
                    throw;
                }
            }
            catch (Exception exception)
            {
                throw;
            }


            return base.FileExists(controllerContext, virtualPath);
        }

    }
}